//
//  DnPhotoGalleryServices.m
//  DnPhotoGalleryDemo
//
//  Created by Ngoc on 13/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#define kDnPhotoGalleryImagesFolder [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DnPhoto"]

#import "DnPhotoGalleryServices.h"

@interface DnPhotoGalleryServices(Private)
-(NSString*) galleryPath;
-(void) doAction:(DnPhotoImageFileAction) action filePaths:(NSArray*) filePaths sourceFolder:(NSString*) sourceFolder destFolder:(NSString*) destFolder;
-(NSString*) getFullPathAndCreateDirIfNeeded:(NSString*) folderName;
-(NSString*) getThumbnailFullPath:(NSString*) fullPath;
-(BOOL) saveImageToLibrary:(UIImage*) image;
@end

@implementation DnPhotoGalleryServices
@synthesize delegate = _delegate;

-(NSString*) getRandomName
{
    return [NSString stringWithFormat:@"%f",CACurrentMediaTime()];
}
-(NSString*) saveImage:(UIImage*) image toFolderName:(NSString*) folderName
{
    NSString *fullPath;
    @try {
        NSString *extension = @".png";
        NSString *path = [self getFullPathAndCreateDirIfNeeded:folderName];
        NSString *fileName= [[self getRandomName] stringByAppendingString:extension];
        fullPath = [path stringByAppendingPathComponent:fileName];
        //    [UIImageJPEGRepresentation(image,1.0f) writeToFile:fullPath atomically:YES];
        [UIImagePNGRepresentation(image) writeToFile:fullPath atomically:YES];
    }
    @catch (NSException *exception) {
        NSLog(@"SAVE IMAGE ERROR: %@", exception.accessibilityHint);
    }

    return fullPath;
}
-(BOOL) saveImageToLibrary:(UIImage*) image
{
//    CGSize size = image.size;
//    UIGraphicsBeginImageContext(size);
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    return YES;
}
-(BOOL) saveImagesToLibrary:(NSArray*) images
{
    if (!_imagesQueue) {
        _imagesQueue = [[NSMutableArray alloc]init ];
    }
    [_imagesQueue addObjectsFromArray:images];
    [self saveImageToLibrary:[_imagesQueue objectAtIndex:0]];
    return YES;
}
- (void)image:(UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
     //[image autorelease];
    if(error != nil) {
        NSLog(@"SAVE IMAGE INCOMPLETE");
        NSLog(@"ERROR SAVING:%@",[error localizedDescription]);
    }
    if (_imagesQueue && [_imagesQueue count]>0)
    {
        [_imagesQueue removeObjectAtIndex:0];
        if([_imagesQueue count]>0) {
            [self saveImageToLibrary:[_imagesQueue objectAtIndex:0] ];
        }
        else
        {
            if (_delegate && [_delegate respondsToSelector:@selector(imageServiceSaveImagesDone:)]) {
                [_delegate imageServiceSaveImagesDone:self];
            }
        }
    }
   
}
-(void) doAction:(DnPhotoImageFileAction) action filePaths:(NSArray*) filePaths sourceFolder:(NSString*) sourceFolder destFolder:(NSString*) destFolder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    switch (action) {
        case DnPhotoFileCopy:
        {
            NSString * fullPath;
            NSString *fullFolderPath;// = [[self galleryPath] stringByAppendingPathComponent:destFolder];
            for (NSString* filePath in filePaths)
            {
                fullFolderPath = [[self galleryPath] stringByAppendingPathComponent:destFolder];
                fullFolderPath = [fullFolderPath stringByAppendingPathComponent:[filePath lastPathComponent]];
                fullPath = [[self galleryPath] stringByAppendingPathComponent:filePath];
                if ([fileManager fileExistsAtPath:fullPath]) {
                    [fileManager copyItemAtPath:fullPath toPath:fullFolderPath error:&error];
                }
            }
            break;
        }   
        case DnPhotoFileDelete:
        {
            NSString *thumbnailPath;
            NSMutableArray *folders = [[NSMutableArray alloc]init ];
            NSString *lastFolderPath = nil;
            NSString *folderPath;
            for (NSString* filePath in filePaths)
            {
                folderPath = [ filePath stringByDeletingLastPathComponent];
                thumbnailPath = filePath;
                filePath = [[self galleryPath] stringByAppendingPathComponent:filePath];
                if ([fileManager fileExistsAtPath:filePath]) {
                    [fileManager removeItemAtPath:filePath error:&error];
                    if (![folderPath isEqualToString: lastFolderPath]) {
                        [folders addObject:folderPath];
                        lastFolderPath = folderPath;
                    }
                }
                thumbnailPath =  [self getThumbnailFullPath:thumbnailPath];
                if ([fileManager fileExistsAtPath:thumbnailPath] ) {
                    [fileManager removeItemAtPath:thumbnailPath error:&error];
                } 
                
            }
            // Delete empty folder
            NSMutableArray *emptyFolders=[[NSMutableArray alloc]init ];
            
            for (NSString* folder in folders) {
                if ([self numberImageOfFolder:folder]==0) {
                    [emptyFolders addObject:folder];
                }
            }
            [self deleteFolders:emptyFolders];
            [folders release];
            [emptyFolders release];
            break;
        }
        case DnPhotoFileMove:
        {
            //NSString *folder;
            NSString *thumbnailPath;
            NSString *thumbnailFolder = [self getFullPathAndCreateDirIfNeeded:[destFolder stringByAppendingPathComponent:@"thumbs"]];
            NSString *fullPath;
            for (NSString* filePath in filePaths) {
                fullPath = [[self galleryPath] stringByAppendingPathComponent:filePath];
                if ([fileManager fileExistsAtPath:fullPath] ) {
                    [fileManager moveItemAtPath:fullPath toPath: [[[self galleryPath] stringByAppendingPathComponent: destFolder]stringByAppendingPathComponent:[filePath lastPathComponent]] error:&error];
                    
                    //folder = [filePath stringByDeletingLastPathComponent];
                    
                    thumbnailPath =  [self getThumbnailFullPath:filePath];
                    thumbnailFolder = [thumbnailFolder stringByAppendingPathComponent:[thumbnailPath lastPathComponent]];
                    if ([fileManager fileExistsAtPath:thumbnailPath] ) {
                        [fileManager moveItemAtPath:thumbnailPath toPath:thumbnailFolder error:&error];
                    }
                }
            }
            break;
        }
        case DnPhotoFolderDelete:
        {
            for(NSString* folderPath in filePaths)
            {
                NSString *path = [[self galleryPath] stringByAppendingPathComponent:folderPath];
                if ([fileManager fileExistsAtPath:path]) {
                        [fileManager removeItemAtPath:path error:&error];
                        //NSLog(@"Delete folder error:%@", error);
                }
            }
            break;
        }
    }
}
-(BOOL) isExistFile:(NSString*) filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:filePath];
}
-(void) moveFiles:(NSArray*) filePaths toFolder:(NSString*) destFolder
{
    [self doAction:DnPhotoFileMove filePaths:filePaths sourceFolder:nil destFolder:destFolder];
    
}
-(void) moveFolder:(NSString*) sourceFolder toFolder:(NSString*) destFolder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray* files = [fileManager contentsOfDirectoryAtPath:sourceFolder error:&error];
    [self moveFiles:files toFolder:destFolder];
}

-(void) deleteFiles:(NSArray*) filePaths
{
    [self doAction:DnPhotoFileDelete filePaths:filePaths sourceFolder:nil destFolder:nil];
}
-(void) copyFiles:(NSArray*) filePaths toFolder:(NSString*) destFolder
{
    [self doAction:DnPhotoFileCopy filePaths:filePaths sourceFolder:nil destFolder:destFolder];
}
-(void) deleteFolders:(NSArray*) folderPaths
{
    [self doAction:DnPhotoFolderDelete filePaths:folderPaths sourceFolder:nil destFolder:nil];
}
//UIImage *DecompressUIImage(UIImage *image) {
//    ATByteImage *byteImage = [[[ATByteImage alloc] initWithImage:image] autorelease];
//    return [byteImage extractImage];
//}
-(NSString*) getThumbnailFullPath:(NSString*) fullPath
{
    NSString *thumbnailPath = [fullPath stringByDeletingPathExtension];
    NSString *extension = [fullPath pathExtension];
    NSString *folder = [fullPath stringByDeletingLastPathComponent];
    folder = [folder stringByAppendingPathComponent:@"thumbs"];
    NSString *fileNameWithoutExtension = [[fullPath lastPathComponent]stringByDeletingPathExtension];
    thumbnailPath = [self getFullPathAndCreateDirIfNeeded:folder];
    thumbnailPath = [thumbnailPath stringByAppendingPathComponent:fileNameWithoutExtension];
    thumbnailPath = [thumbnailPath stringByAppendingString:[NSString stringWithFormat:@"_thumb.%@",extension]];
    return thumbnailPath;
}
-(UIImage*) getThumbnailImageFromPath:(NSString*) filePath size:(CGSize) size
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    UIImage *croppedImage;
    NSString * fullPath = [[self galleryPath] stringByAppendingPathComponent:filePath];
    UIImage *sourceImage = [UIImage imageWithContentsOfFile:fullPath];
    NSString *thumbnailPath =[self getThumbnailFullPath:filePath];
    if ([fileManager fileExistsAtPath:thumbnailPath]) {
        croppedImage = [UIImage imageWithContentsOfFile:thumbnailPath];
    }
    else
    {
        float ratio = size.width/size.height;
        CGRect croppedRect;
        if (sourceImage.size.width<sourceImage.size.height) {
            croppedRect.size = CGSizeMake(sourceImage.size.width, sourceImage.size.width*(1/ratio));
        }
        else
        {
            croppedRect.size = CGSizeMake(sourceImage.size.height *ratio, sourceImage.size.height);
        }
        CGPoint center = CGPointMake(sourceImage.size.width/2, sourceImage.size.height/2);
        croppedRect.origin = CGPointMake(center.x - croppedRect.size.width/2, center.y - croppedRect.size.height/2);
        croppedImage = [sourceImage croppedImage:croppedRect];
        croppedImage = [croppedImage resizedImage:size interpolationQuality:kCGInterpolationMedium];
        [UIImagePNGRepresentation(croppedImage) writeToFile:thumbnailPath atomically:YES];
    }
    
    return croppedImage;
}
-(NSArray*) getImagePathsInFolder:(NSString*) folder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *fullPath = [[self galleryPath] stringByAppendingPathComponent:folder];
    NSArray *extensions = [NSArray  arrayWithObjects:@"jpg", @"png", nil];
    NSArray *files = [fileManager contentsOfDirectoryAtPath:fullPath error:&error];
    NSArray *onlyImageFile = [files filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension IN %@" ,extensions]];
    return onlyImageFile;
}

-(NSArray*) foldersInsideGallery
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *folders ;//= [fileManager contentsOfDirectoryAtPath:[self galleryPath] error:&error];
    NSURL *url = [NSURL fileURLWithPath:[self galleryPath]];
    folders = [fileManager contentsOfDirectoryAtURL:url includingPropertiesForKeys:[NSArray arrayWithObject:NSURLNameKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:&error];
    NSMutableArray * returnFolders = [[[NSMutableArray alloc]init ]autorelease];
    for (NSURL* folder in folders) {
        [returnFolders addObject:[[folder path] lastPathComponent]];
    }
    return returnFolders;
}

-(NSString*) galleryPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    if (![fileManager fileExistsAtPath:kDnPhotoGalleryImagesFolder])
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager createDirectoryAtPath:kDnPhotoGalleryImagesFolder
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
    }
    
    return kDnPhotoGalleryImagesFolder;
}
-(NSString*) getFullPathAndCreateDirIfNeeded:(NSString*) folderName
{
    NSString *fullPath =[self galleryPath];
    fullPath = [fullPath stringByAppendingPathComponent:folderName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    if (![fileManager fileExistsAtPath:fullPath])
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager createDirectoryAtPath:fullPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
    }
    
    return fullPath;
}
-(NSInteger) numberFolderOfGallery
{
    return [[self foldersInsideGallery]count];
}
-(NSInteger) numberImageOfFolder:(NSString*) folder
{
    return [[self getImagePathsInFolder:folder]count];
}
@end
